package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import splug.cjk.packet.FriendPacket;

public class FriendAdd extends Thread{

	private InputStream is;
	private OutputStream os;
	private String id;
	private String you;

	public FriendAdd(InputStream is, OutputStream os) {
		super();
		this.is = is;
		this.os = os;
	}

	public void run(){
		try {
			ObjectInputStream input = new ObjectInputStream(is);
			FriendPacket packet = (FriendPacket) input.readObject();

			String id = packet.getId();
			String you = packet.getYou();

			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/carpool?useUnicode=true&characterEncoding=euckr","root","apmsetup");
			Statement stmt = conn.createStatement();

			String query2 = "select f, t from friend";

			ResultSet rs = stmt.executeQuery(query2);

			while(rs.next()){
				String str1 = rs.getString("f");
				String str2 = rs.getString("t");
				if(str1.equals(id) && str2.equals(you)){
					os.write('2');
					os.flush();
					return;
				}
			}

			String query1 = "select id from member;";

			rs = stmt.executeQuery(query1);

			while(rs.next()){
				String str = rs.getString("id");
				if(str.equals(you)){
					String query = "INSERT INTO `carpool`.`friend` (`f` ,`t` ,`accept`) " +
							"VALUES ('" + id + "','" + you + "', 0);";

					stmt.execute("SET CHARACTER SET euckr");
					stmt.execute("set names euckr");

					stmt.executeUpdate(query);

					os.write('1');
					os.flush();
					return;
				}

			}

			os.write('0');
			os.flush();

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			try {
				os.write('0');
				os.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
